package org.zjt.chapter1.promise;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.zjt.chapter1.Chapter1Server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.sun.tools.doclint.Entity.prod;
import static org.zjt.chapter1.Chapter1Client.PORT;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-12-03 8:45 PM
 * @see
 */
@Slf4j
public class PromiseServer {


    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new DiscardServerHandler());
                        }
                    });

            // Start the server.
            ChannelFuture f = b.bind(PORT).addListener(future -> log.info(future.isSuccess()? "连接成功" :"连接失败")).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }



    public static class DiscardServerHandler extends ChannelInboundHandlerAdapter {

        ExecutorService executorService = Executors.newFixedThreadPool(4);

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {

            ByteBuf data = ByteBuf.class.cast(msg);
            byte[] bytes = new byte[data.readableBytes()];
            data.readBytes(bytes);

            System.out.println("server receive "+new String(bytes));

            // 创建一个DefaultPromise并返回，利用executor来通知Promise执行结果。
            EventExecutor executor = ctx.executor();
            DefaultPromise<String> promise = new DefaultPromise<String>(executor);

            // 执行业务逻辑
            executorService.submit(() -> {
                try {
                    System.out.println(String.format("	>>search price of %s from internet!",prod));

                    // 等待5S后设置future为成功，
                    Thread.sleep(5000);
                    promise.setSuccess("$99.99");
                } catch (InterruptedException e) {
                    e.printStackTrace();

                    //当然，也可以设置失败
                    promise.setFailure(new NullPointerException());
                }
            });

            // promise 是可监听的 future
            promise.addListener(future -> {
                Object object = future.get();
                ctx.writeAndFlush(Unpooled.wrappedBuffer(String.valueOf(object).getBytes()));
            });
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            // Close the connection when an exception is raised.
            cause.printStackTrace();
            ctx.close();
        }
    }
}
